<?php
/**
 * Description:
 * Author: JennyWang
 * Date: 2018/9/1
 * Time: 15:44
 * Created by PhpStorm.
 */

namespace App\Services\Repositories;


use App\Http\Models\Admin\Product;
use App\Http\Models\Admin\ProductCategory;
use App\Services\Utils\ApiChecker;
use Illuminate\Pagination\LengthAwarePaginator;

class ProductionRepository
{
    use ApiChecker;
    
    protected $product;
    
    public function __construct()
    {
        $this->product = new Product;
    }
    
    
    /**
     * @param $product_category_id
     * @param $keyword
     * @param $per_page
     * @return mixed
     * @throws \App\Exceptions\AdminManageException
     */
    public function index($product_category_id,
                          $keyword, $per_page = 15)
    {
        if ($product_category_id) {
        
            /** @var ProductCategory $product_category */
            $product_category = ProductCategory::find($product_category_id);
                $this->checkItemExist($product_category, '产品种类');
    
            /** @var LengthAwarePaginator $production */
            $production = $product_category->products()
                ->filterKeyWord($keyword)
                ->latest('sort')
                ->paginate($per_page);
        } else {  // 搜索标题或者型号
            $production = Product::filterKeyWord($keyword)
                ->latest('sort')
                ->paginate($per_page);
        }
    
        $production->getCollection()->each(function (Product $product){
            $this->appendProductLink($product);
        });
    
        return $production;
    }
    
    /**
     * @param int $id
     *
     * @return Product
     * @throws \App\Exceptions\AdminManageException
     */
    public function findOrFail($id)
    {
        $product = $this->product->find($id);
            $this->checkItemExist($id);
        
        return $product;
    }
    
    /**
     * @param Product $product
     */
    public function appendProductLink(Product $product)
    {
        $qs = '?'. http_build_query([
            'pid' => $product->product_category_id,
            'detail_id' => $product->id
        ]);
        
        $product->link = url('production') . $qs;
    }
}